﻿using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Math;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Reflection;
using System.Security.Principal;
using System.Threading.Tasks;
using static AutoMapper.Internal.CollectionMapperExpressionFactory;

namespace Coldairarrow.Business.Base_Manage
{
    /// <summary>
    ///操作OL采购需求业务逻辑
    /// </summary>
    public class OL_CaptureBusiness
    {
        public IDbAccessor Db { get; set; }
        /// <summary>
        /// 操作ol采购需求对象
        /// </summary>
        public KD_AP_PAYBILL_APIInterfaceBusiness _KD_AP_PAYBILL_API { get; set; }

        public OL_CaptureBusiness(IDbAccessor db)
        {
            this.Db = db;
            _KD_AP_PAYBILL_API = new KD_AP_PAYBILL_APIInterfaceBusiness();
        }


        public async Task<string> Verify(List<AP_PAYBILL_SAVEDTO> items)
        {

            return await Task.Run(() =>
            {
                List<string> result = new List<string>();
                _KD_AP_PAYBILL_API.SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:K3ConnectionString");
                string orgId = "";
                foreach (var item1 in items)
                {
                    //表头
                    foreach (var item2 in item1.data.Model)
                    {
                        try
                        {
                            //付款组织
                            List<T_DB_BaseDate> t_org_organizations = _KD_AP_PAYBILL_API.SqlDb.GetListBySql<T_DB_BaseDate>($@"
select a.FORGID ID,a.FNUMBER,b.FNAME from t_org_organizations(NOLOCK) a
LEFT JOIN t_org_organizations_l(NOLOCK) b ON  a.FORGID=b.FORGID AND b.FLOCALEID='2052'
where b.FNAME='{item2.FPAYORGID.FNUMBER}'");
                            if (t_org_organizations.IsNullOrEmpty() || t_org_organizations.Count == 0) throw new Exception($"金蝶推送报错:法歌帝生活科技（广东）有限公司不存在 付款主体({item2.FRECTUNIT.FNUMBER})，请到金蝶维护");
                            orgId = t_org_organizations[0].ID;

                            //收款组织
                            List<T_DB_BaseDate> T_BD_SUPPLIER = _KD_AP_PAYBILL_API.SqlDb.GetListBySql<T_DB_BaseDate>($@"
select a.FSUPPLIERID ID,a.FNUMBER,b.FNAME from T_BD_SUPPLIER(NOLOCK) a
LEFT JOIN T_BD_SUPPLIER_L(NOLOCK) b ON  a.FSUPPLIERID=b.FSUPPLIERID  AND b.FLOCALEID='2052'
where b.FNAME='{item2.FRECTUNIT.FNUMBER}' AND a.FUSEORGID='{orgId}'");
                            if (T_BD_SUPPLIER.IsNullOrEmpty() || T_BD_SUPPLIER.Count == 0) throw new Exception($"金蝶推送报错:法歌帝生活科技（广东）有限公司不存在 收款主体({item2.FRECTUNIT.FNUMBER})，请到金蝶维护");

//                            //银行账号
//                            List<T_DB_BaseDate> T_CN_BANKACNT = _KD_AP_PAYBILL_API.SqlDb.GetListBySql<T_DB_BaseDate>($@"
//SELECT a.FBANKID ID,a.FNUMBER,b.FNAME FROM T_CN_BANKACNT(NOLOCK) a
//LEFT JOIN T_CN_BANKACNT_L(NOLOCK) b ON  a.FBANKACNTID=b.FBANKACNTID AND b.FLOCALEID='2052'
//where a.FNUMBER='{item2.FPAYBILLENTRY.First().FACCOUNTID.FNUMBER}' AND a.FUSEORGID='{orgId}'");
//                            if (T_CN_BANKACNT.IsNullOrEmpty() || T_CN_BANKACNT.Count == 0) throw new Exception($"金蝶推送报错:法歌帝生活科技（广东）有限公司不存在 银行账号({item2.FPAYBILLENTRY.First().FACCOUNTID.FNUMBER})，请到金蝶维护");

                            //币别
                            List<T_DB_BaseDate> T_BD_CURRENCY = _KD_AP_PAYBILL_API.SqlDb.GetListBySql<T_DB_BaseDate>($@"
SELECT a.FCURRENCYID ID,a.FNUMBER,b.FNAME FROM T_BD_CURRENCY a
LEFT JOIN T_BD_CURRENCY_L b ON  a.FCURRENCYID=b.FCURRENCYID AND b.FLOCALEID='2052'
where b.FNAME='{item2.FCURRENCYID.FNUMBER}'");
                            if (T_BD_CURRENCY.IsNullOrEmpty() || T_BD_CURRENCY.Count == 0) throw new Exception($"金蝶推送报错:法歌帝生活科技（广东）有限公司不存在 币别({item2.FCURRENCYID.FNUMBER})，请到金蝶维护");

                        }
                        catch (Exception ex)
                        {
                            result.Add(ex.Message);
                        }

                        foreach (var item3 in item2.FPAYBILLENTRY)
                        {
                            try
                            {

                                //结算方式
                                List<T_DB_BaseDate> T_BD_SETTLETYPE = _KD_AP_PAYBILL_API.SqlDb.GetListBySql<T_DB_BaseDate>($@"
select a.FID ID,a.FNUMBER,b.FNAME from T_BD_SETTLETYPE(NOLOCK)  a
LEFT JOIN T_BD_SETTLETYPE_L(NOLOCK) b ON  a.FID=b.FID AND b.FLOCALEID='2052'
where b.FNAME='{item3.FSETTLETYPEID.FNUMBER}'");
                                if (T_BD_SETTLETYPE.IsNullOrEmpty() || T_BD_SETTLETYPE.Count == 0) throw new Exception($"金蝶推送报错:法歌帝生活科技（广东）有限公司不存在 结算方式({item3.FSETTLETYPEID.FNUMBER})，请到金蝶维护");

                                //费用项目
                                List<T_DB_BaseDate> T_BD_EXPENSE = _KD_AP_PAYBILL_API.SqlDb.GetListBySql<T_DB_BaseDate>($@"
SELECT a.FEXPID ID,a.FNUMBER,b.FNAME FROM T_BD_EXPENSE(NOLOCK) a
LEFT JOIN T_BD_EXPENSE_L(NOLOCK) b ON  a.FEXPID=b.FEXPID AND b.FLOCALEID='2052'
where b.FNAME='{item3.FEXPENSEDEPTID_E.FNUMBER} '");
                                if (T_BD_EXPENSE.IsNullOrEmpty() || T_BD_EXPENSE.Count == 0) throw new Exception($"金蝶推送报错:法歌帝生活科技（广东）有限公司不存在 费用项目({item3.FCOSTID.FNUMBER})，请到金蝶维护");
                                //部门
                                List<T_DB_BaseDate> T_BD_DEPARTMENT = _KD_AP_PAYBILL_API.SqlDb.GetListBySql<T_DB_BaseDate>($@"
SELECT a.FDEPTID ID,a.FNUMBER,b.FNAME FROM T_BD_DEPARTMENT(NOLOCK) a
LEFT JOIN T_BD_DEPARTMENT_L(NOLOCK) b ON  a.FDEPTID=b.FDEPTID AND b.FLOCALEID='2052'
where b.FNAME='{item3.FCOSTID.FNUMBER}'AND a.FUSEORGID='{orgId}'");
                                if (T_BD_DEPARTMENT.IsNullOrEmpty() || T_BD_DEPARTMENT.Count == 0) throw new Exception($"金蝶推送报错:法歌帝生活科技（广东）有限公司不存在 部门({item3.FEXPENSEDEPTID_E.FNUMBER})，请到金蝶维护");
                            }
                            catch (Exception ex)
                            {
                                result.Add(ex.Message);
                            }

                        }

                    }
                }

                if (result.Count > 0)
                {
                    return string.Join("=====\r\n", result);
                }
                else
                {
                    return "OK";
                }


            });

        }


        /// <summary>
        /// 将数据推送到金蝶
        /// </summary>
        /// <param name="newItems"></param>
        /// <returns></returns>
        public async Task<string> PushToKingdee(List<AP_PAYBILL_SAVEDTO> items)
        {


            //返回消息列表
            List<string> msg = new List<string>();
            //
            bool isOK = true;
            await Task.Run(() =>
            {
                _KD_AP_PAYBILL_API.SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:K3ConnectionString");
                string orgId = "";
                foreach (var item1 in items)
                {
                    //表头
                    foreach (var item2 in item1.data.Model)
                    {
                        try
                        {
                            //单据类型
                            //if (item2.FBillTypeID.FNUMBER.Contains("供应商（物料类"))
                            //{
                            //    item2.FBillTypeID.FNUMBER = "FKDLX01_SYS";
                            //}
                            //else
                            //{
                            //    item2.FBillTypeID.FNUMBER = "FKDLX02_SYS";
                            //}



                            //付款组织
                            List<T_DB_BaseDate> t_org_organizations = _KD_AP_PAYBILL_API.SqlDb.GetListBySql<T_DB_BaseDate>($@"
select a.FORGID ID,a.FNUMBER,b.FNAME from t_org_organizations(NOLOCK) a
LEFT JOIN t_org_organizations_l(NOLOCK) b ON  a.FORGID=b.FORGID AND b.FLOCALEID='2052'
where b.FNAME='{item2.FPAYORGID.FNUMBER}'");
                            if (t_org_organizations.IsNullOrEmpty() || t_org_organizations.Count == 0) throw new Exception($"金蝶推送报错:法歌帝生活科技（广东）有限公司不存在 付款主体({item2.FPAYORGID.FNUMBER})，请到金蝶维护");
                            else item2.FPAYORGID.FNUMBER = t_org_organizations.First().FNUMBER;
                            orgId = t_org_organizations[0].ID;

                            //收款组织
                            List<T_DB_BaseDate> T_BD_SUPPLIER = _KD_AP_PAYBILL_API.SqlDb.GetListBySql<T_DB_BaseDate>($@"
select a.FSUPPLIERID ID,a.FNUMBER,b.FNAME from T_BD_SUPPLIER(NOLOCK) a
LEFT JOIN T_BD_SUPPLIER_L(NOLOCK) b ON  a.FSUPPLIERID=b.FSUPPLIERID  AND b.FLOCALEID='2052'
where b.FNAME='{item2.FRECTUNIT.FNUMBER}' AND a.FUSEORGID='{orgId}' AND a.FFORBIDSTATUS='A' ");
                            if (T_BD_SUPPLIER.IsNullOrEmpty() || T_BD_SUPPLIER.Count == 0) throw new Exception($"金蝶推送报错:法歌帝生活科技（广东）有限公司不存在 收款主体({item2.FRECTUNIT.FNUMBER})，请到金蝶维护");
                            else
                            {
                                item2.FRECTUNIT.FNUMBER = T_BD_SUPPLIER.First().FNUMBER;
                                item2.FCONTACTUNIT.FNUMBER = T_BD_SUPPLIER.First().FNUMBER;
                            } 

                            //币别
                            List<T_DB_BaseDate> T_BD_CURRENCY = _KD_AP_PAYBILL_API.SqlDb.GetListBySql<T_DB_BaseDate>($@"
SELECT a.FCURRENCYID ID,a.FNUMBER,b.FNAME FROM T_BD_CURRENCY a
LEFT JOIN T_BD_CURRENCY_L b ON  a.FCURRENCYID=b.FCURRENCYID AND b.FLOCALEID='2052'
where b.FNAME='{item2.FCURRENCYID.FNUMBER}'");
                            if (T_BD_CURRENCY.IsNullOrEmpty() || T_BD_CURRENCY.Count == 0) throw new Exception($"金蝶推送报错:法歌帝生活科技（广东）有限公司不存在 币别({item2.FCURRENCYID.FNUMBER})，请到金蝶维护");
                            else item2.FCURRENCYID.FNUMBER = T_BD_CURRENCY.First().FNUMBER;
                        }
                        catch (Exception ex)
                        {
                            msg.Add(ex.Message);
                            isOK = false;
                        }

                        foreach (var item3 in item2.FPAYBILLENTRY)
                        {
                            try
                            {
                                //单据类型
                                //if (item2.FBillTypeID.FNUMBER.Contains("FKDLX01_SYS"))//采购付款单类型
                                //{
                                //    item2.FBillTypeID.FNUMBER = "FKDLX01_SYS";
                                //}
                                //else
                                //{
                                //    item2.FBillTypeID.FNUMBER = "FKDLX02_SYS";
                                //}
                                //结算方式
                                List<T_DB_BaseDate> T_BD_SETTLETYPE = _KD_AP_PAYBILL_API.SqlDb.GetListBySql<T_DB_BaseDate>($@"
select a.FID ID,a.FNUMBER,b.FNAME from T_BD_SETTLETYPE(NOLOCK)  a
LEFT JOIN T_BD_SETTLETYPE_L(NOLOCK) b ON  a.FID=b.FID AND b.FLOCALEID='2052'
where b.FNAME='{item3.FSETTLETYPEID.FNUMBER}'");
                                if (T_BD_SETTLETYPE.IsNullOrEmpty() || T_BD_SETTLETYPE.Count == 0) throw new Exception($"金蝶推送报错:法歌帝生活科技（广东）有限公司不存在 结算方式({item3.FSETTLETYPEID.FNUMBER})，请到金蝶维护");
                                else item3.FSETTLETYPEID.FNUMBER = T_BD_SETTLETYPE.First().FNUMBER;
                                //银行账号
                                List<T_DB_BaseDate> T_CN_BANKACNT = _KD_AP_PAYBILL_API.SqlDb.GetListBySql<T_DB_BaseDate>($@"
SELECT a.FBANKID ID,a.FNUMBER,b.FNAME FROM T_CN_BANKACNT(NOLOCK) a
LEFT JOIN T_CN_BANKACNT_L(NOLOCK) b ON  a.FBANKACNTID=b.FBANKACNTID AND b.FLOCALEID='2052'
where a.FNUMBER='{item3.FACCOUNTID.FNUMBER}' AND a.FUSEORGID='{orgId}'");
                                if (T_CN_BANKACNT.IsNullOrEmpty() || T_CN_BANKACNT.Count == 0) throw new Exception($"金蝶推送报错:法歌帝生活科技（广东）有限公司不存在 银行账号({item3.FACCOUNTID.FNUMBER})，请到金蝶维护");
                                else item3.FACCOUNTID.FNUMBER = T_CN_BANKACNT.First().FNUMBER;
                                //费用项目
                                List<T_DB_BaseDate> T_BD_EXPENSE = _KD_AP_PAYBILL_API.SqlDb.GetListBySql<T_DB_BaseDate>($@"
SELECT a.FEXPID ID,a.FNUMBER,b.FNAME FROM T_BD_EXPENSE(NOLOCK) a
LEFT JOIN T_BD_EXPENSE_L(NOLOCK) b ON  a.FEXPID=b.FEXPID AND b.FLOCALEID='2052'
where b.FNAME='{item3.FEXPENSEDEPTID_E.FNUMBER} '");
                                if (T_BD_EXPENSE.IsNullOrEmpty() || T_BD_EXPENSE.Count == 0) throw new Exception($"金蝶推送报错:法歌帝生活科技（广东）有限公司不存在 费用项目({item3.FCOSTID.FNUMBER})，请到金蝶维护");
                                else item3.FEXPENSEDEPTID_E.FNUMBER = T_BD_EXPENSE.First().FNUMBER;
                                //部门
                                List<T_DB_BaseDate> T_BD_DEPARTMENT = _KD_AP_PAYBILL_API.SqlDb.GetListBySql<T_DB_BaseDate>($@"
SELECT a.FDEPTID ID,a.FNUMBER,b.FNAME FROM T_BD_DEPARTMENT(NOLOCK) a
LEFT JOIN T_BD_DEPARTMENT_L(NOLOCK) b ON  a.FDEPTID=b.FDEPTID AND b.FLOCALEID='2052'
where b.FNAME='{item3.FCOSTID.FNUMBER}'AND a.FUSEORGID='{orgId}'");
                                if (T_BD_DEPARTMENT.IsNullOrEmpty() || T_BD_DEPARTMENT.Count == 0) throw new Exception($"金蝶推送报错:法歌帝生活科技（广东）有限公司不存在 部门({item3.FEXPENSEDEPTID_E.FNUMBER})，请到金蝶维护");
                                else item3.FCOSTID.FNUMBER = T_BD_DEPARTMENT.First().FNUMBER;
                            }
                            catch (Exception ex)
                            {
                                msg.Add(ex.Message);
                                isOK = false;
                            }

                        }

                    }
                }



            });
            if (msg.Count() > 0) isOK = false;


            //执行推送
            if (isOK)
            {
                msg = await _KD_AP_PAYBILL_API.ExecuteNoQuery<AP_PAYBILL_SAVEDTO>(items, _KD_AP_PAYBILL_API.BatchSave, _KD_AP_PAYBILL_API.SqlDb);
            }


            return string.Join("=====\r\n", msg);
        }


    }
}